package com.cuiweiyou.happypaint.util;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class GsonUtil {
    static Gson gson = new GsonBuilder().serializeNulls().create();

    public static String mapToJson(Map<String, Object> map) {
        return gson.toJson(map);
    }

    public static Map<String, Object> jsonToMap(String json) {
        Type type = new TypeToken<HashMap<String, Object>>() {
        }.getType();
        return gson.fromJson(json, type);
    }

    public static <T> T jsonToBean(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static String listToJson(List list) {
        return gson.toJson(list);
    }

    public static <T> List<T> jsonToList(Class<T> clazz, String jsonString) {
        List result = new ArrayList();
        JsonElement jsonElement = JsonParser.parseString(jsonString);
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        Iterator it = jsonArray.iterator();
        while (it.hasNext()) {
            jsonElement = (JsonElement) it.next();
            String json = jsonElement.toString();
            T obj = gson.fromJson(json, clazz);
            result.add(obj);
        }
        return result;
    }
}
